package edison.utils;

import java.net.URISyntaxException;
import java.net.URL;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;

import javax.jcr.RepositoryException;

import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.Element;
import org.dom4j.io.SAXReader;

import edison.persistence.Dialect;

public abstract class Configuration {

	private static Dialect dialect;
	private static Map<String, String> cfg;

	public static Map<String, String> getCongfiguration() throws DocumentException, URISyntaxException {
		if (cfg == null)
			cfg = ReadConfiguration();

		return cfg;
	}

	@SuppressWarnings("rawtypes")
	private static Map<String, String> ReadConfiguration() throws DocumentException, URISyntaxException {
		URL fileURL = Configuration.class.getClassLoader().getResource("META-INF/cfg.xml");
		SAXReader reader = new SAXReader();
		Document document = reader.read(fileURL);
		Element root = document.getRootElement();
		Map<String, String> map = new HashMap<String, String>();
		for (Iterator i = root.elementIterator(); i.hasNext();) {
			Element element = (Element) i.next();
			String name = element.attributeValue("name");
			String value = element.attributeValue("value");
			map.put(name, value);
		}

		return map;
	}

	

	public static Dialect getDialect() throws RepositoryException {
		if (dialect == null) {
			try {
				Map<String, String> cfg = Configuration.getCongfiguration();
				Class<?> c = Class.forName(cfg.get("dialect"));
				dialect = (Dialect) c.newInstance();
			} catch (Exception e) {
				throw new RepositoryException(e);
			}
		}

		return dialect;

	}

}
